package com.kangdi.aitranslate.controller;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.List;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.function.Supplier;

import com.alibaba.cloud.ai.dashscope.chat.DashScopeChatModel;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.File;
import java.io.FileOutputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;

@RestController
public class TestController {

    @Autowired
    private DashScopeChatModel chatClient;

    // 创建带缓存的线程池
    private static final ExecutorService translationExecutor =
            Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() * 2);

    private void processParagraph(List<String> paragraphs,
                                  StringBuilder targetResult,
                                  String sourceLang,
                                  String targetLang,
                                  String fileType) {
        try {
            // 创建带索引的翻译任务列表
            List<CompletableFuture<TranslatedParagraph>> futures = new ArrayList<>();

            for (int i = 0; i < paragraphs.size(); i++) {
                final String paragraph = paragraphs.get(i);
                final int index = i;

                CompletableFuture<TranslatedParagraph> future = CompletableFuture.supplyAsync(() -> {
                    // 带重试的翻译调用
                    return retryTranslate(() -> {
                        String prompt = String.format(
                                "你是一个专业翻译，将以下%s内容从%s精准翻译为%s。要求：\n" +
                                        "1. 严格保留所有格式符号（如Markdown语法、HTML标签）\n" +
                                        "2. 保留数字、特殊符号和代码块\n" +
                                        "3. 保持原始排版结构\n" +
                                        "待翻译内容：%s",
                                fileType, sourceLang, targetLang, paragraph);

                        return new TranslatedParagraph(index, chatClient.call(prompt));
                    }, 3); // 最大重试次数
                }, translationExecutor).exceptionally(e -> {
                    System.err.println("Translation failed after retries: " + paragraph);
                    return new TranslatedParagraph(index, paragraph); // 失败时返回原文
                });

                futures.add(future);
            }

            // 批量获取结果并排序
            CompletableFuture.allOf(futures.toArray(new CompletableFuture[0]))
                    .get(2, TimeUnit.MINUTES); // 总超时时间

            futures.stream()
                    .map(CompletableFuture::join)
                    .sorted(Comparator.comparingInt(TranslatedParagraph::index))
                    .forEach(tp -> targetResult.append(tp.content()).append("\n\n"));

        } catch (Exception e) {
            System.err.println("Error processing paragraphs batch: " + e.getMessage());
            paragraphs.forEach(p -> targetResult.append(p).append("\n\n"));
        }
    }

    // 带重试机制的翻译方法
    private TranslatedParagraph retryTranslate(Supplier<TranslatedParagraph> translator, int maxRetries) {
        int retries = 0;
        while (retries < maxRetries) {
            try {
                return translator.get();
            } catch (Exception e) {
                retries++;
                if (retries == maxRetries) {
                    throw new RuntimeException("Translation failed after " + maxRetries + " attempts", e);
                }
                try {
                    Thread.sleep(1000 * retries); // 指数退避
                } catch (InterruptedException ie) {
                    Thread.currentThread().interrupt();
                }
            }
        }
        throw new IllegalStateException("Unexpected error in retry logic");
    }

    // 翻译段落记录类
    private record TranslatedParagraph(int index, String content) {
    }


    @PostMapping("testFile")
    public ResponseEntity<FileSystemResource> testFile(@RequestParam MultipartFile file,
                                                       @RequestParam String sourceLanguage,
                                                       @RequestParam String targetLanguage) throws IOException {
        StringBuilder result = new StringBuilder();
        List<String> paragraphs = new ArrayList<>();
        StringBuilder currentParagraph = new StringBuilder();
        String fileName = file.getOriginalFilename();
        String fileType = "text";

        // 检测文件类型
        if (fileName != null) {
            if (fileName.endsWith(".md")) {
                fileType = "markdown";
            } else if (fileName.endsWith(".html")) {
                fileType = "html";
            } else if (fileName.endsWith(".pdf")) {
                fileType = "pdf";
            }
        }

        try (InputStream inputStream = file.getInputStream();
             BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8))) {

            String line;
            while ((line = reader.readLine()) != null) {
                // 合并段落逻辑：连续非空行视为一个段落
                if (!line.trim().isEmpty()) {
                    currentParagraph.append(line).append("\n");
                } else {
                    if (currentParagraph.length() > 0) {
                        paragraphs.add(currentParagraph.toString());
                        currentParagraph.setLength(0);
                    }
                    result.append("\n");
                }
            }
            // 处理最后一个段落
            if (currentParagraph.length() > 0) {
                paragraphs.add(currentParagraph.toString());
            }
        }
        processParagraph(paragraphs, result, sourceLanguage, targetLanguage, fileType);

        // 创建临时文件（带随机后缀避免冲突）
        File tempFile = new File(fileName);
        try (FileOutputStream fos = new FileOutputStream(tempFile)) {
            fos.write(result.toString().getBytes());
        }
        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION,
                        "attachment; filename=\"" + new String(fileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1) + "\"; filename*=utf-8''" + URLEncoder.encode(fileName, StandardCharsets.UTF_8))
                .contentType(MediaType.APPLICATION_OCTET_STREAM)
                .body(new FileSystemResource(tempFile));
    }
}
